<!DOCTYPE html>
<!--
Copyright 2015 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->
<link rel="import" href="/tracing/base/guid.html">
<link rel="import" href="/tracing/base/utils.html">
<link rel="import" href="/tracing/base/xhr.html">
<link rel="import" href="/tracing/extras/full_config.html">
<link rel="import" href="/tracing/importer/import.html">
<link rel="import" href="/tracing/model/model.html">

<script>
'use strict';

tr.exportTo('tr.mre', function() {
  function FileHandle(canonicalUrl) {
    this.canonicalUrl_ = canonicalUrl;
  }

  FileHandle.prototype = {
    get canonicalUrl() { return this.canonicalUrl_; },

    asDict() {
      const d = {
        canonical_url: this.canonicalUrl_
      };

      this.asDictInto_(d);
      if (d.type === undefined) {
        throw new Error('asDictInto_ must set type field');
      }
    },

    load() {
      throw new Error('Not implemented');
    }
  };

  FileHandle.fromDict = function(handleDict) {
    if (handleDict.type === 'url') {
      return URLFileHandle.fromDict(handleDict);
    }
    if (handleDict.type === 'in-memory') {
      return InMemoryFileHandle.fromDict(handleDict);
    }

    throw new Error('Not implemented: fromDict for ' + handleDict.type);
  };


  function URLFileHandle(canonicalUrl, urlToLoad) {
    // TODO(eakuefner): assert startswith file://
    FileHandle.call(this, canonicalUrl);
    this.urlToLoad = urlToLoad;
    this.loadAsTraceStream_ = false;
  }

  URLFileHandle.prototype = {
    __proto__: FileHandle.prototype,

    asDictInto_(handleDict) {
      handleDict.urlToLoad = this.urlToLoad;
      handleDict.type = 'url';
    },

    load() {
      try {
        return tr.b.getSync(this.urlToLoad, this.loadAsTraceStream_);
      } catch (ex) {
        const err = new Error('Could not open ' + this.urlToLoad);
        err.name = 'FileLoadingError';
        throw err;
      }
    }
  };


  URLFileHandle.fromDict = function(handleDict) {
    return new URLFileHandle(handleDict.canonical_url, handleDict.url_to_load);
  };

  function InMemoryFileHandle(fileData, canonicalUrl) {
    FileHandle.call(this, canonicalUrl);
    this.fileData = fileData;
  }

  InMemoryFileHandle.prototype = {
    __proto__: FileHandle.prototype,

    asDictInto_(handleDict) {
      handleDict.data = this.fileData;
      handleDict.type = 'in-memory';
    },

    load() {
      return this.fileData;
    }
  };

  InMemoryFileHandle.fromDict = function(handleDict) {
    return new InMemoryFileHandle(
        handleDict.data, handleDict.canonical_url);
  };

  return {
    FileHandle,
    URLFileHandle,
    InMemoryFileHandle,
  };
});
</script>
